/*
Copyright © 2025 NAME HERE <EMAIL ADDRESS>
*/
package cmd

import (
	"common-cobra/pak"
	"context"
	"fmt"
	"strconv"
	"strings"

	"github.com/c-bata/go-prompt"
	"github.com/go-redis/redis"
	"github.com/spf13/cobra"
)

var (
	ctx    = context.Background()
	client *redis.Client
)

func NewRedisClient(addr, password string, db int) *redis.Client {
	return redis.NewClient(&redis.Options{
		Addr:     addr,     // 格式: "host:port"‌:ml-citation{ref="2,3" data="citationList"}
		Password: password, // 密码（无则为空）‌:ml-citation{ref="2,7" data="citationList"}
		DB:       db,       // 数据库编号‌:ml-citation{ref="3,7" data="citationList"}
	})
}

func executor(input string) {
	input = strings.TrimSpace(input)
	if input == "" {
		return
	}

	// 分割命令参数并执行‌:ml-citation{ref="3,7" data="citationList"}
	args := strings.Fields(input)
	cmd := client.Do(ctx, args)
	res, err := cmd.Result()

	// 错误处理
	if err != nil {
		fmt.Printf("(error) %v\n", err)
		return
	}

	// 结果格式化输出‌:ml-citation{ref="1,7" data="citationList"}
	switch v := res.(type) {
	case string:
		fmt.Printf("\"%s\"\n", v)
	case []interface{}:
		for i, item := range v {
			fmt.Printf("%d) %v\n", i+1, item)
		}
	default:
		fmt.Printf("%v\n", v)
	}
}

// redisCmd represents the redis command
var redisCmd = &cobra.Command{
	Use:   "redis",
	Short: "A brief description of your command",
	Long:  `function for conn redis like: redis  0.0.0.0 6379  password,仅用于可证明redis可以连接`,
	Args:  cobra.ExactArgs(3),
	Run: func(cmd *cobra.Command, args []string) {
		port, err := strconv.Atoi(args[1])
		if err != nil {
			fmt.Println("端口格式错误!")
			return
		}
		url := fmt.Sprintf("%s:%d", args[0], port)
		client = NewRedisClient(url, args[2], 0)
		defer client.Close()

		if _, err := client.Ping().Result(); err != nil {
			panic("连接失败: " + err.Error())
		}

		// 启动交互终端
		p := prompt.New(
			executor,
			pak.Completer,
			prompt.OptionPrefix("127.0.0.1:6379> "),
		)
		p.Run()
	},
}

func init() {
	rootCmd.AddCommand(redisCmd)
}
